package com.skymobi.netty.demo.biz;

import com.skymobi.netty.demo.bean.GetUrlRequest;
import com.skymobi.netty.demo.bean.GetUrlResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import stc.skymobi.fsm.FSMContext;
import stc.skymobi.fsm.FiniteStateMachine;
import stc.skymobi.fsm.tmpl.annotation.OnAccept;
import stc.skymobi.fsm.tmpl.annotation.OnEnter;
import stc.skymobi.fsm.tmpl.annotation.StateTemplate;
import stc.skymobi.netty.handler.codec.http.response.SendbackResponseHelper;
import stc.skymobi.netty.transport.Sender;
import stc.skymobi.netty.transport.TransportUtils;

public class GetUrlBiz extends BaseBiz<GetUrlRequest, GetUrlResponse> {
    private static final Logger logger = LoggerFactory.getLogger(GetUrlBiz.class);

    private SendbackResponseHelper sendbackResponseHelper;

    @StateTemplate(init = true)
    class RecvReq {
        @OnAccept
        Class<?> accept(FiniteStateMachine fsm, FSMContext ctx, final GetUrlRequest req) {
            logger.debug("accept event: {}", req);
            setRequest(ctx, req);

            GetUrlResponse resp = new GetUrlResponse();
            String url = req.getUrl();
            resp.setResponse(url);
            resp.setToken(req.getToken() + 1);
            resp.setIdentification(req.getIdentification());
            setResponse(ctx, resp);

            return SendbackResp.class;
        }
    }

    @StateTemplate
    class SendbackResp {
        @OnEnter
        @SuppressWarnings("unchecked")
        boolean enter(FiniteStateMachine fsm, FSMContext ctx) {
            GetUrlRequest req = getRequest(ctx);
            GetUrlResponse response = getResponse(ctx);

            Sender sender = TransportUtils.getSenderOf(req);
            logger.debug("SendClientRespState={}", response);

            if (sender != null) {
                sender.send(response);
            } else {
                sendbackResponseHelper.makeAndSendback(getResponse(ctx), req);
            }
            ctx.setEndReason("SUCCESS");
            return false;
        }
    }

    public void setSendbackResponseHelper(SendbackResponseHelper sendbackResponseHelper) {
        this.sendbackResponseHelper = sendbackResponseHelper;
    }
}
